import FlagImage from '@/components/FlagImage';
import TagTags from '@/components/TagTags';
import * as c from '@/services/consts';
import * as apiEvent from '@/services/idcApiEvent';
import * as apiGroup from '@/services/vpnGroup';
import * as api from '@/services/vpnServerMonitor';
import * as utils from '@/utils/utils';
import {
  AreaChartOutlined,
  ArrowDownOutlined,
  ArrowRightOutlined,
  ArrowUpOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
  ExclamationCircleFilled,
  InfoCircleOutlined,
  PartitionOutlined,
  ProfileOutlined,
  ReloadOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';
import ProTable, {
  ActionType,
  ColumnsState,
  ProColumns,
} from '@ant-design/pro-table';
import {
  Badge,
  Button,
  Checkbox,
  Col,
  message,
  Popconfirm,
  Radio,
  Row,
  Space,
  Tag,
} from 'antd';
import { CheckboxValueType } from 'antd/es/checkbox/Group';
import Paragraph from 'antd/es/typography/Paragraph';
import Countdown from 'antd/lib/statistic/Countdown';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import CheckTaskForm from '../CheckTask/CheckForm';
import CheckTaskReportForm from '../CheckTask/CheckReportForm';
import GroupForm from '../VpnGroup/components/Form';
import SyncIpForm from '../VpnServer/components/SyncIpForm';
import VpnServerExportIpForm from '../VpnServer/components/VpnServerExportIpForm';
import VpnServerForm from '../VpnServer/components/VpnServerForm';
import CheckForm from '../VpnServerCheckLog/CheckForm';
import CheckReportForm from '../VpnServerCheckLog/CheckReportForm';
import GrafanaForm from './components/GrafanaForm';
import OnlineForm from './components/OnlineForm';
import ReportIpForm from './components/ReportIpsForm';
const dateFormat = 'YYYY-MM-DD';
import ChangeIpLogStatusTag from '@/components/ChangeIpLogTag';
import CheckLogTipTag from '@/components/CheckLogTipTag';
import { DeployLogStatusTag } from '@/components/StatusTag';
import DeployForm from '../Deploy/DeployForm';

const VpnGroupTreeList: React.FC = (props: any) => {
  // const { match } = props;
  // const paramOnline = parseInt(match.params.a, undefined);
  // console.log('location:', location, ' match: ', match, match?.params?.a);

  let paramOnline: any = utils.getStateValue('online');
  // console.log(paramOnline);

  const [dataLoading, setDataLoading] = useState<boolean>(true);
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.VpnServer | undefined>(undefined);
  const [productId, setProductId] = useState<string | undefined>(undefined);

  const [formGrafanaVisible, setFormGrafanaVisible] = useState<boolean>(false);
  // const [formChangeIpVisible, setFormChangeIpVisible] =useState<boolean>(false);
  const [currentNodeGroup, setCurrentNodeGroup] = useState<
    API.VpnGroupMonitorModel | undefined
  >(undefined);
  const [currentNode, setCurrentNode] = useState<
    API.VpnServerMonitorModel | undefined
  >(undefined);
  const [currentUrlGrafana, setCurrentUrlGrafana] = useState<
    string | undefined
  >(undefined);
  const [levelGroups, setLevelGroups] = useState<
    API.VpnGroupMonitorModel[] | undefined
  >(undefined);
  const [grafanaTitle, setGrafanaTitle] = useState<string | undefined>(
    undefined,
  );

  const [formCheckVisible, setFormCheckVisible] = useState<boolean>(false);
  const [formCheckReportVisible, setFormCheckReportVisible] =
    useState<boolean>(false);
  const [checkGroupIds, setCheckGroupIds] = useState<string[]>([]);
  // const [checkGroups, setCheckGroups] = useState<API.VpnGroupMonitorModel[]>([],);
  const [checkServerInstIds, setCheckServerInstIds] = useState<number[]>([]);
  const [checkServers, setCheckServers] = useState<API.VpnServerMonitorModel[]>(
    [],
  );
  const [formCheckTaskReportVisible, setFormCheckTaskReportVisible] =
    useState<boolean>(false);

  const [formGroupVisible, setFormGroupVisible] = useState<boolean>(false);
  const [currentGroup, setCurrentGroup] = useState<
    API.VpnGroupMonitorModel | undefined
  >(undefined);
  const [formOnlineVisible, setFormOnlineVisible] = useState<boolean>(false);
  const [currentOnlineCode, setCurrentOnlineCode] = useState<
    string | undefined
  >(undefined);
  const [formExportIpVisible, setFormExportIpVisible] =
    useState<boolean>(false);
  const [formReportIpVisible, setFormReportIpVisible] =
    useState<boolean>(false);

  const [filterAreaPolicy, setFilterAreaPolicy] = useState<number | undefined>(
    undefined,
  );
  const [filterStatus, setFilterStatus] = useState<boolean | undefined>(
    undefined,
  );
  const [filterOnline, setFilterOnline] = useState<number | undefined>(
    paramOnline,
  );
  const [filterMemberLevel, setFilterMemberLevel] = useState<any[]>([-1]);
  const [filterTag, setFilterTag] = useState<string[]>(['-1']);
  const [currentVer, setCurrentVer] = useState<string | undefined>(undefined);
  const [filterGroupType, setFilterGroupType] = useState<any[]>(['all']);

  const [countdownTicks, setCountdownTicks] = useState<number>(-1);
  //   Date.now() + 60000,
  // );

  const [monitorData, setMonitorData] = useState<
    API.VpnGroupMonitorList | undefined
  >(undefined);
  // const [controlState, setControlState] = useState<number>(0);

  const [columnsStateMap, setColumnsStateMap] = useState<
    Record<string, ColumnsState>
  >({
    // 'areaPolicy':{show:false},
    displayAppVerComparePolicy: { show: false },
    displayPlatforms: { show: false },
    displayChannels: { show: false },
    isp: { show: false },
  });
  // const [selectedTags, setSelectedTags] = useState<string[]>([
  //   'group',
  //   'server',
  // ]);

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const { hasRight } = useModel('useAuthModel');

  const {
    // getProduct,
    getProductMenuItems,
    getSupplier,
    getGroupAreaFilterPolicyText,
    reloadVpnGroupTrees,
    globalGrafanaModel,
    tags,
    getGeoipIsp,
    setDeployConfigPublish,
  } = useModel('useGlobalModel', (model) => ({
    // getProduct: model.getProduct,
    getProductMenuItems: model.getProductMenuItems,
    getSupplier: model.getSupplier,
    getGroupAreaFilterPolicyText: model.getGroupAreaFilterPolicyText,
    reloadVpnGroupTrees: model.reloadVpnGroupTrees,
    globalGrafanaModel: model.globalGrafanaModel,
    tags: model.tags,
    getGeoipIsp: model.getGeoipIsp,
    setDeployConfigPublish: model.setDeployConfigPublish,
  }));

  const productMenuItems = getProductMenuItems(true);
  const alertGreen = 104857600; //100*1024*1024
  const alertOrange = 209715200; //200*1024*1024
  // const alertOrangeMb = 250;//200 / 0.8; //200*1024*1024
  const [formCheckTaskVisible, setFormCheckTaskVisible] =
    useState<boolean>(false);
  // const [groupExpandedRowKeys, setGroupExpandedRowKeys] = useState<any>([]);
  const [formSyncIpVisible, setFormSyncIpVisible] = useState<boolean>(false);
  const [formDeployVisible, setFormDeployVisible] = useState<boolean>(false);
  const [selectServer, setSelectServer] = useState<API.VpnServerMonitorModel[] | undefined>(undefined);

  const reload = () => {
    // if (countdownTicks > 0) {
    // setControlState(new Date().getTime());
    // setCountdownTicks(Date.now() + customCountdownTicks);
    // setCountdownTicks(Date.now() + 60000);
    // }
    loadDataDo();
  };

  const loadDataDo = async () => {
    const result = await api.list(
      {
        productIds:
          productId && productId !== c.DefaultOptionAll.key
            ? parseInt(productId)
            : undefined,
        areaPolicy: filterAreaPolicy,
        // disableGroup: filterDisableGroup,
        // disableServer: filterDisableServer,
        online: filterOnline,
        status: filterStatus,
        memberLevels: filterMemberLevel,
        tags: filterTag,
        groupType: filterGroupType,
      },
      undefined,
      undefined,
    );

    if (result && result.success) {
      setMonitorData(result);
    } else {
      // setMonitorData([]);
      setMonitorData(undefined);
    }
    setDataLoading(false);
    setCountdownTicks(Date.now() + 60000);
  };

  useEffect(() => {
    setDataLoading(true);
    setCountdownTicks(-1);
    loadDataDo();
  }, [productId, filterAreaPolicy, filterOnline, filterStatus, filterMemberLevel, filterTag, filterGroupType]);//controlState, 

  const getTagOptions = () => {
    let options: any[] = [];

    for (let item of tags) {
      options.push({
        label: item.name,
        value: item.id,
        disabled: !item.status,
      });
    }

    return options;
  };

  const handleCheckGroup = async (model: API.VpnGroupMonitorModel) => {
    if (!checkGroupIds.includes(model.id)) {
      let ids = checkGroupIds.concat([model.id]);
      // console.log(ids);
      setCheckGroupIds(ids);
      // setCheckGroups(checkGroups.concat(model));
      setFormCheckTaskVisible(true);
      //   message.info('设置成功，等待下发');
      // } else {
      //   message.info('已经存在');
    }
    else{
      setFormCheckTaskVisible(true);
    }
  };

  const handleCheckServer = async (model: API.VpnServerMonitorModel) => {
    if (!checkServerInstIds.includes(model.instanceId)) {
      let ids = checkServerInstIds.concat([model.instanceId]);
      // console.log(ids);
      setCheckServerInstIds(ids);
      setCheckServers(checkServers.concat(model));
      setFormCheckTaskVisible(true);
      //   message.info('设置成功，等待下发');
      // } else {
      //   message.info('已经存在');
    }
    else{
      setFormCheckTaskVisible(true);
    }
  };

  // const handleFilterAreaPolicy = (val: number | undefined) => {
  //   setFilterAreaPolicy(val);
  //   setDataLoading(true);
  //   reload();
  // };

  // const handleFilterOnline = (val: number | undefined) => {
  //   setFilterOnline(val);
  //   setDataLoading(true);
  //   reload();
  // };

  // const handleFilterStatus = (val: boolean | undefined) => {
  //   setFilterStatus(val);
  //   setDataLoading(true);
  //   reload();
  // };

  const handleFilterGroupType = (checkedValue: CheckboxValueType[]) => {
    if (filterGroupType.includes('all')) {
      if (checkedValue.length == 1) {
        setFilterGroupType(['all']);
      } else {
        setFilterGroupType(checkedValue.filter((val) => val != 'all'));
      }
    } else if (checkedValue.includes('all')) {
      setFilterGroupType(['all']);
    } else if (checkedValue.length == 0) {
      setFilterGroupType(['all']);
    } else {
      setFilterGroupType(checkedValue);
    }
  };

  const handleFilterMemberLevel = (checkedValue: CheckboxValueType[]) => {
    if (filterMemberLevel.includes(-1)) {
      if (checkedValue.length == 1) {
        setFilterMemberLevel([-1]);
      } else {
        setFilterMemberLevel(checkedValue.filter((val) => val != -1));
      }
    } else if (checkedValue.includes(-1)) {
      setFilterMemberLevel([-1]);
    } else if (checkedValue.length == 0) {
      setFilterMemberLevel([-1]);
    } else {
      setFilterMemberLevel(checkedValue);
    }
  };

  const handleFilterTag = (checkedValue: any[]) => {
    if (filterTag.includes('-1')) {
      if (checkedValue.length == 1) {
        setFilterTag(['-1']);
      } else {
        setFilterTag(checkedValue.filter((val) => val != '-1'));
      }
    } else if (checkedValue.includes('-1')) {
      setFilterTag(['-1']);
    } else if (checkedValue.length == 0) {
      setFilterTag(['-1']);
    } else {
      setFilterTag(checkedValue);
    }
    // setDataLoading(true);
    // reload();
  };

  const handleFilterReset = () => {
    setFilterAreaPolicy(undefined);
    setFilterStatus(undefined);
    setFilterOnline(paramOnline);
    setFilterMemberLevel([-1]);
    setFilterTag(['-1']);
    setFilterGroupType(['all']);
    setDataLoading(true);
    reload();
  };

  const checkFormSubmit = async () => {
    setFormCheckVisible(false);
    setCheckGroupIds([]);
    setCheckServerInstIds([]);
    // setCheckGroups([]);
    setCheckServers([]);
  };

  const handleFormGroupSubmit = async (
    record: API.VpnGroupModel | API.VpnGroupMonitorModel,
  ) => {
    record.mutiLangs = record.mutiLangs ? record.mutiLangs : {};
    if (!record.userLimit) {
      record.userLimit = undefined;
    }
    let d: API.VpnGroupModel = {
      id: record.id, // ?? currentGroup?.id,
      name: record.name, // ?? currentGroup?.name,
      code: record.code, // ?? currentGroup?.code,
      mutiLang: record.mutiLang, // ?? currentGroup?.mutiLang,
      flag: record.flag, // ?? currentGroup?.flag,
      type: record.type, // ?? currentGroup?.type,
      memberLevel: record.memberLevel, // ?? currentGroup?.memberLevel,
      userLimit: record.userLimit, //  ?? currentGroup?.userLimit,
      sort: record.sort, //  ?? currentGroup?.sort,
      tags: record.tags, // ?? currentGroup?.tags,
      parentId: record.parentId, // ?? currentGroup?.parentId,
      preBridgeGroupIds: record.preBridgeGroupIds,
      display: record.display,
      blacklistGroup: record.blacklistGroup,
      status: record.status, // ?? currentGroup?.status,
      remark: record.remark, // ?? currentGroup?.remark,
      changeIp: record.changeIp, // ?? currentGroup?.changeIp,
      changeIpCount: record.changeIpCount,
      policy: record.policy, // ?? currentGroup?.policy,
      allotMode: record.allotMode, // ?? currentGroup?.allotMode,
      allotConfig: record.allotConfig, // ?? currentGroup?.allotConfig,
      protocol: record.protocol, // ?? currentGroup?.protocol,
      productIds: record.productIds, // ??  currentGroup?.productIds,
      productIdsText: '',
      parentSort: 0,
      secondSort: 0,
      serverCount: 0,
      validServerCount: 0,
      userCount: 0,
    };

    // console.log(d);
    // return;

    let result = await apiGroup.update({
      // ...currentGroup,
      // ...record,
      ...d,
    });

    if (result && result.success === true) {
      setCurrentGroup(undefined);
      setFormGroupVisible(false);
      setDataLoading(true);
      reload();

      //更新缓存
      await reloadVpnGroupTrees();
    }
  };


  const alertRateMb = (
    rate: number | undefined,
    rateTotal: number | undefined,
    per1: number,
    per2: number,
    isByte: boolean,
  ) => {
    if (!rate) return 0;
    if (isByte == false) {
      rate = rate / 8;
    }
    rate = rate / 1024 / 1024;

    rateTotal = rateTotal ?? 250; //200 /0.8

    // console.log(rate, rateTotal, rateTotal * per1, rateTotal * per2);

    let ar = rate > rateTotal * per1;
    if (ar == true) {
      ar = rate > rateTotal * per2;
      if (ar == true) {
        return 3;
      } else {
        return 2;
      }
    }
    return 1;
  };

  const handleChangeIp = async (
    supplierId: number | undefined,
    instId: number | undefined,
  ) => {
    if (!supplierId) {
      message.error('该服务器没有提供商');
      return;
    }

    // let supplier = getSupplier(supplierId);
    // if(!supplier){
    //   message.error("未找到该服务器提供商");
    //   return;
    // }
    // if(!supplier.code){
    //   message.error("该服务器提供商未设置代码");
    //   return;
    // }

    if (!instId) {
      message.error('请选择检测内容');
      return;
    }

    let record: API.IdcApiEventForm = {
      // code: supplier.code,
      action: c.IdcApiEventAction.ChangeIp.value,
      // supplierId: supplierId,
      instanceIds: instId.toFixed(),
    };

    // console.log(record);
    // return false;
    const result = await apiEvent.add(record);
    if (result && result.success) {
      message.success('下发成功，等待处理中');
      reload();
    }
  };

  let columns: ProColumns<API.VpnGroupMonitorModel>[] = [
    {
      title: '状态',
      align: 'center',
      width: 60,
      dataIndex: 'status',
      sorter: (a, b) => (a.status == true ? 1 : 0) - (b.status == true ? 1 : 0),
      // valueEnum: {
      //   true: { status: 'Success' },
      //   false: { status: 'Error' },
      // },
      renderText: (val) => {
        return val ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
    },
    // {
    //   title: '产品',
    //   // align: 'center',
    //   width: 90,
    //   dataIndex: 'productIdsText',
    //   // sorter: (a, b) => (a.parentId ?? '').localeCompare(b.parentId ?? ''),
    //   renderText: (_, record) => {
    //     if (record.productIds) {
    //       let text = '';
    //       for (let i = 0; i < record.productIds.length; i++) {
    //         const product = getProduct(record.productIds[i]);
    //         if (product) {
    //           if (text != '') {
    //             text += '/';
    //           }
    //           text += product.name;
    //         }
    //       }

    //       return text;
    //     }
    //     return '';
    //   },
    // },
    {
      title: '等级',
      align: 'center',
      width: 60,
      dataIndex: 'memberLevel',
      sorter: (a, b) => (a.memberLevel ?? 0) - (b.memberLevel ?? 0),
      renderText: (val) => {
        return c.getMemberLevelText(val);
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      sorter: (a, b) => (a.name ?? '').localeCompare(b.name ?? ''),
      width: 300,
      render: (text, record) => {
        // let title = `${text}`;
        let title = (
          <>
            {text}[{record.code}]
          </>
        );

        // if(record.protocol){
        //   title = <span style={{color:record.protocol == 3 ? '#54ba05' : record.protocol == 1 ? "blue" : record.protocol == 2 ? "#c08af3" : ""}}>{text}</span>;
        // }

        // if (record.children != null) {
        //   title += ` (${record.serverCount}/${record.children.length})`;
        // } else {
        //   title += ` (${record.serverCount})`;
        // }

        return (
          <>
            <Space>
              <Paragraph
                copyable={{ text: text.toString() }}
                style={{ marginBottom: 0 }}
              >
                <FlagImage flagName={record.flag} />
                {record.display != true ? <Tag>{title}</Tag> : title}{' '}
                {record.preBridgeGroups && record.preBridgeGroups.length > 0 ? (
                  <Tag color="blue">桥接</Tag>
                ) : (
                  ''
                )}
                {record.policy?.cheaterId == c.CheaterType.TcpCheaterCdn.value ? (
                  <Tag color="blue">CDN</Tag>
                ) : (
                  ''
                )}
                {record.changeIp > 0 ? (
                  <Tag color="blue">{record.changeIp}分钟</Tag>
                ) : (
                  ''
                )}
                {record.type == c.VpnGroupType.Ghost.value ? (
                  <>
                    <Tag color="green" style={{ marginLeft: 5 }}>
                      {c.getVpnGroupTypeText(record.type)}
                    </Tag>
                  </>
                ) : (
                  ''
                )}
              </Paragraph>
            </Space>
            <a
              key="check_group_title"
              onClick={(e) => {
                handleCheckGroup(record);
              }}
            >
              <PartitionOutlined style={{ color: '#999', marginLeft: 5 }} />
            </a>
          </>
        );
      },
    },
    {
      title: '启用/总数',
      // align: 'center',
      dataIndex: 'validServerCount',
      width: 100,
      sorter: (a, b) => (a.validServerCount ?? 0) - (b.validServerCount ?? 0),
      renderText: (_, record) => {
        if (record.validServerCount == 0) {
          return (
            <Tag color="red">
              {record.validServerCount}/{record.serverCount}
            </Tag>
          );
        }
        return `${record.validServerCount}/${record.serverCount}`;
      },
    },
    {
      title: '在线/离线',
      // align: 'center',
      dataIndex: 'onlineCount',
      width: 100,
      sorter: (a, b) => (a.onlineCount ?? 0) - (b.onlineCount ?? 0),
      renderText: (_, record) => {
        if (record.onlineCount == 0) {
          return (
            <Tag color="red">
              {record.onlineCount}/{record.offlineCount}
            </Tag>
          );
        }
        return (
          <>
            {record.onlineCount}/
            {record.offlineCount ? (
              <span style={{ color: '#f50', fontWeight: 'bold' }}>
                {record.offlineCount}
              </span>
            ) : (
              record.offlineCount
            )}
          </>
        );
      },
    },
    {
      title: 'Helper',
      // align: 'center',
      dataIndex: 'helperOnlineCount',
      width: 100,
      sorter: (a, b) => (a.helperOnlineCount ?? 0) - (b.helperOnlineCount ?? 0),
      renderText: (_, record) => {
        if (record.helperOnlineCount == 0) {
          return (
            <Tag color="orange">
              {record.helperOnlineCount}/{record.helperOfflineCount}
            </Tag>
          );
        }
        return (
          <>
            {record.helperOnlineCount}/
            {record.helperOfflineCount ? (
              <span style={{ color: 'orange', fontWeight: 'bold' }}>
                {record.helperOfflineCount}
              </span>
            ) : (
              record.helperOfflineCount
            )}
          </>
        );
      },
    },
    {
      title: 'IP总/禁/墙/出',
      // align: 'center',
      dataIndex: 'ipCount',
      width: 130,
      sorter: (a, b) => (a.ipCount ?? 0) - (b.ipCount ?? 0),
      renderText: (_, record) => {
        return (
          <>
            {record.ipCount}/
            {record.ipDisableCount ? (
              <span style={{ color: '#f50', fontWeight: 'bold' }}>
                {record.ipDisableCount}
              </span>
            ) : (
              record.ipDisableCount
            )}
            /
            {record.ipBlockCount ? (
              <span style={{ color: 'orange', fontWeight: 'bold' }}>
                {record.ipBlockCount}
              </span>
            ) : (
              record.ipBlockCount
            )}
            /{record.ipRelayCount}
          </>
        );
      },
    },
    {
      title: '在线用户/限制',
      dataIndex: 'userCount',
      // align: 'center',
      width: 150,
      sorter: (a, b) => (a.userCount ?? 0) - (b.userCount ?? 0),
      render: (_, record) => {
        return (
          <>
            {utils.formatNumber(record.userCount)}
            {record.userLimit ? (
              <span>
                /
                <span style={{ color: 'orange', fontWeight: 'bold' }}>
                  {utils.formatNumber(record.userLimit)}
                </span>
              </span>
            ) : (
              ''
            )}
            <a
              key="online_chart"
              onClick={(e) => {
                setFormOnlineVisible(true);
                setCurrentGroup(record);
                setCurrentOnlineCode(undefined);
              }}
            >
              &nbsp;
              <AreaChartOutlined />
            </a>
            <a
              key="online_ips"
              onClick={(e) => {
                setFormReportIpVisible(true);
                setCurrentGroup(record);
                setCurrent(undefined);
              }}
            >
              &nbsp;
              <ProfileOutlined />
            </a>
          </>
        );
      },
    },
    {
      title: '下载',
      dataIndex: 'download',
      sorter: (a, b) => (a.download ?? 0) - (b.download ?? 0),
      width: 100,
      render: (_, record) => {
        let val = 0;
        if (record.maxBandwidth) {
          val = alertRateMb(
            record.download,
            record.maxBandwidth,
            0.7,
            0.9,
            true,
          );
        } else {
          val =
            record.upload && record.validServerCount > 0
              ? record.upload / record.validServerCount
              : 0;
          val =
            val == 0 ? 0 : val <= alertGreen ? 1 : val <= alertOrange ? 2 : 3;
        }
        return (
          <Tag
            color={
              val == 3 ? 'red' : val == 2 ? 'orange' : val == 1 ? 'green' : ''
            }
          >
            <b>
              <ArrowDownOutlined /> {utils.formatRate(record.download, true)}
            </b>
          </Tag>
        );
      },
    },
    {
      title: '上传',
      dataIndex: 'upload',
      sorter: (a, b) => (a.upload ?? 0) - (b.upload ?? 0),
      width: 125,
      render: (_, record) => {
        let val = 0;
        if (record.maxBandwidth) {
          val = alertRateMb(record.upload, record.maxBandwidth, 0.7, 0.9, true);
        } else {
          val =
            record.upload && record.validServerCount > 0
              ? record.upload / record.validServerCount
              : 0;
          val =
            val == 0 ? 0 : val <= alertGreen ? 1 : val <= alertOrange ? 2 : 3;
        }
        return (
          <span>
            <Tag
              color={
                val == 3 ? 'red' : val == 2 ? 'orange' : val == 1 ? 'green' : ''
              }
            >
              <b>
                <ArrowUpOutlined /> {utils.formatRate(record.upload, true)}
              </b>
            </Tag>
            <a
              key="edit"
              onClick={(e) => {
                // setFormNodeGroupVisible(true);
                // setCurrentNodeGroup(record);
                setFormGrafanaVisible(true);
                setCurrentNode(undefined);
                setCurrentNodeGroup(record);
                // setCurrentUrlGrafana(urlGrafanaNodeGroup);
                setCurrentUrlGrafana(globalGrafanaModel?.urlGrafanaNodeGroup);
                setLevelGroups(undefined);
              }}
            >
              <AreaChartOutlined />
            </a>
          </span>
        );
      },
    },
    {
      title: '分组代码',
      dataIndex: 'code',
      width: 90,
      sorter: (a, b) => (a.code ?? '').localeCompare(b.code ?? ''),
      render: (_, record) => {
        return (
          <>
            {record.preBridgeGroups.length > 0 ? (
              <div>
                {record.preBridgeGroups?.map((val) => (
                  <Tag color="blue">{val.code}</Tag>
                ))}
              </div>
            ) : (
              ''
            )}
            <div>
              {record.preBridgeGroups.length > 0 ? <ArrowRightOutlined /> : ''}
              {record.code}
            </div>
          </>
        );
      },
    },
    {
      title: '支持协议',
      // align: 'center',
      dataIndex: 'protocol',
      sorter: true,
      width: 90,
      renderText: (val) => {
        return val ? (
          <Tag color="blue">{c.getObjectText(c.VpnGroupProtocols, val)}</Tag>
        ) : (
          ''
        );
      },
    },
    {
      title: '版本策略',
      dataIndex: 'displayAppVerComparePolicy',
      width: 80,
      // align: 'center',
      sorter: false,
      renderText: (_, record) => {
        if (
          record.policy != null &&
          record.policy.displayAppVerComparePolicy &&
          record.policy.displayAppVerComparePolicy != '' &&
          record.policy.displayAppVerComparePolicyAppVer > 0
        ) {
          return `${record.policy.displayAppVerComparePolicy}${record.policy.displayAppVerComparePolicyAppVer}`;
        }
        return null;
      },
    },
    {
      title: '平台策略',
      dataIndex: 'displayPlatforms',
      width: 80,
      sorter: false,
      renderText: (_, record) => {
        return record.policy?.displayPlatforms?.join(',');
      },
    },
    {
      title: '渠道策略',
      dataIndex: 'displayChannels',
      width: 80,
      sorter: false,
      renderText: (_, record) => {
        return record.policy?.displayChannels?.join(',');
      },
    },
    {
      title: '地区策略',
      width: 120,
      dataIndex: 'areaPolicy',
      sorter: false,
      render: (_, record) => {
        let policy = getGroupAreaFilterPolicyText(record.policy);
        return policy ? (
          <Tag color={policy.indexOf('显示') == -1 ? '' : 'blue'}>{policy}</Tag>
        ) : (
          policy
        );
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      width: 150,
      render: (_, record) => <TagTags values={record.tags} />,
    },
    {
      title: 'ISP运营商',
      dataIndex: 'isp',
      width: 120,
      render: (_, record) => {
        if (!record.policy?.ispFilterPolicyIspList) {
          return <></>;
        }
        var lines = [];
        for (let item of record.policy.ispFilterPolicyIspList) {
          var name = getGeoipIsp(item)?.name;
          if (
            record.policy.ispFilterPolicy == c.IspFilterPolicy.Whitelist.value
          ) {
            lines.push(<Tag color="green">{name}</Tag>);
          } else {
            lines.push(<Tag color="orange">{name}</Tag>);
          }
        }
        return lines;
      },
    },
    {
      title: 'IP墙数/昨',
      // align: 'center',
      dataIndex: 'ipBlacklistCount',
      width: 95,
      sorter: (a, b) => (a.ipBlacklistCount ?? 0) - (b.ipBlacklistCount ?? 0),
      renderText: (_, record) => {
        return (
          <>
            {record.ipBlacklistCount >= 0 ? record.ipBlacklistCount : '--'} / {record.ipBlacklistCount1d >= 0 ? record.ipBlacklistCount1d : '--'}
          </>
        );
      },
    },
    {
      title: '排序',
      align: 'center',
      width: 60,
      dataIndex: 'sort',
      sorter: (a, b) => (a.sort ?? 0) - (b.sort ?? 0),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
      sorter: (a, b) => (a.remark ?? '').localeCompare(b.remark ?? ''),
    },
    {
      title: '最后检测',
      dataIndex: 'checkTime',
      width: 200,
      render: (_, record) => {
        return (
          <>
            <a
              onClick={() => {
                setCurrentVer(record.checkVer);
                setFormCheckTaskReportVisible(true);
                setCurrentNodeGroup(record);
              }}
            >
              <InfoCircleOutlined />
            </a>
            &nbsp;
            <CheckLogTipTag 
              checkAuto={record.checkAuto} 
              checkPercent={record.checkPercent}
              checkTime={record.checkTime}
              checkInterval={monitorData.checkInterval}
              checkFalse={record.checkFalse}
            />
          </>
        );
      },
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 90,
      render: (_, record) => {
        let cmps = [];

        if (hasRight('vpngroup_update')) {
          cmps.push(
            <a
              key="edit_group"
              onClick={(e) => {
                setCountdownTicks(-1);
                setFormGroupVisible(true);
                setCurrentGroup(record);
              }}
            >
              编辑
            </a>,
          );
        }

        if (hasRight('vpnserver_update') && record.status == true) {
          cmps.push(
            <a
              key="check"
              onClick={(e) => {
                handleCheckGroup(record);
              }}
            >
              X检测
            </a>,
          );
        }

        // if (hasRight('vpnserver_update')) {
        //   cmps.push(
        //     <a
        //       key="check_report"
        //       onClick={(e) => {
        //         setCurrentVer(record.checkVer);
        //         setFormCheckReportVisible(true);
        //         setCurrentNodeGroup(record);
        //       }}
        //     >
        //       检测结果
        //     </a>,
        //   );
        // }
        // cmps.push(
        //   <TableDropdown
        //     key="actionGroup"
        //     onSelect={(key) => {
        //       // console.log(key);
        //       switch (key) {
        //         // case 'edit_group':
        //         //   setCountdownTicks(-1);
        //         //   setFormGroupVisible(true);
        //         //   setCurrentGroup(record);
        //         // break;
        //         case 'check_report':
        //           setCurrentVer(record.checkVer);
        //           setFormCheckReportVisible(true);
        //           setCurrentNodeGroup(record);
        //           break;
        //       }
        //     }}
        //     menus={[
        //       { key: 'check_report', name: '检测结果' },
        //       // { key: 'edit_group', name: '编辑分组' },
        //     ]}
        //   />,
        // );

        return cmps;
      },
    },
  ]);

  let childrenColumns: ProColumns<API.VpnServerMonitorModel>[] = [
    {
      title: '状态',
      align: 'center',
      width: 60,
      dataIndex: 'status',
      // sorter: true,
      sorter: (a, b) => (a.status == true ? 1 : 0) - (b.status == true ? 1 : 0),
      // valueEnum: {
      //   true: { status: 'Success' },
      //   false: { status: 'Error' },
      // },
      renderText: (val) => {
        return val ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
    },
    {
      title: '实例ID',
      // align: 'center',
      width: 90,
      dataIndex: 'instanceId',
      //sorter: true,
      sorter: (a, b) => a.instanceId - b.instanceId,
      render: (_, record) => {
        return record.unscheduled == true ? (
          <Tag color="gold">{record.instanceId}</Tag>
        ) : (
          record.instanceId
        );
      },
    },
    {
      title: '类型',
      align: 'center',
      width: 70,
      dataIndex: 'serverType',
      //sorter: true,
      sorter: (a, b) => (a.serverType ?? 0) - (b.serverType ?? 0),
      render: (_, record) => {
        return c.getServerType(record.serverType)?.label;
      },
    },
    {
      title: '供应商',
      align: 'center',
      width: 100,
      dataIndex: 'supplierId',
      //sorter: true,
      sorter: (a, b) => (a.supplierId ?? 0) - (b.supplierId ?? 0),
      render: (_, record) => {
        return getSupplier(record.supplierId)?.name;
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: 230,
      sorter: (a, b) => (a.name ?? '').localeCompare(b.name ?? ''),
      render: (_, record) => {
        return (
          <>
            <div>
              {record.name}
              <a
                key="check_node_title"
                onClick={(e) => {
                  handleCheckServer(record);
                }}
              >
                <PartitionOutlined style={{ color: '#999', marginLeft: 5 }} />
              </a>
            </div>
            {record.serverInfo?.serverName ? (
              <div>
                <Tag color="blue">{record.serverInfo?.serverName}</Tag>
              </div>
            ) : (
              ''
            )}
            
          </>
        );
      },
    },
    {
      title: 'IP总/禁/墙/出',
      dataIndex: 'ip',
      width: 250,
      sorter: (a, b) => (a.ip ?? '').localeCompare(b.ip ?? ''),
      render: (_, record) => {
        return (
          <>
            <div>
              {record.blockedIp == true ||
              (record.remark && record.remark.indexOf('被墙') != -1) ? (
                <span style={{ color: 'orange' }}>{record.ip}</span>
              ) : (
                record.ip
              )}{' '}
              {record.ipCount == 0 ? (
                ''
              ) : (
                <>
                  {' '}
                  ({record.ipCount}/
                  {record.ipDisableCount ? (
                    <span style={{ color: '#f50', fontWeight: 'bold' }}>
                      {record.ipDisableCount}
                    </span>
                  ) : (
                    record.ipDisableCount
                  )}
                  /
                  {record.ipBlockCount ? (
                    <span style={{ color: 'orange', fontWeight: 'bold' }}>
                      {record.ipBlockCount}
                    </span>
                  ) : (
                    record.ipBlockCount
                  )}
                  /{record.ipRelayCount})
                </>
              )}
            </div>

            {record.ipCountry ? (
              <div style={{ color: 'blue' }}>
                {record.ipCountry} - {record.ipProvince}
              </div>
            ) : (
              ''
            )}

            {record.serverInfo?.changeIpLog?.log?.status 
              ? <div><ChangeIpLogStatusTag log={record.serverInfo?.changeIpLog?.log} lastLog={record.serverInfo?.changeIpLog?.lastLog} /></div> : ''}

          </>
        );
      },
    },
    {
      title: '在线',
      align: 'center',
      width: 60,
      dataIndex: 'online',
      sorter: (a, b) => (a.online == true ? 1 : 0) - (b.online == true ? 1 : 0),
      render: (_, record) => {
        return (
          <>
            {record.online ? (
              <Badge
                count={<CheckCircleFilled style={{ color: '#52c41a' }} />}
              />
            ) : (
              <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
            )}
            {record.online == false && record.updateTime ? (
              <div>{record.updateTime}</div>
            ) : (
              ''
            )}
          </>
        );
      },
    },
    {
      title: 'Helper',
      align: 'center',
      width: 70,
      dataIndex: 'helperOnline',
      sorter: (a, b) => (a.helperOnline == true ? 1 : 0) - (b.helperOnline == true ? 1 : 0),
      render: (_, record) => {
        return (
          <>
            {record.helperOnline == true ? (
              <Badge
                count={<CheckCircleFilled style={{ color: '#52c41a' }} />}
              />
            ) : record.helperOnline == false ? (
              <Badge count={<ExclamationCircleFilled style={{ color: 'orange' }} />} />
            ):''}
            {record.helperOnline == false && record.helperOnlineTime ? (
              <div>{utils.formatDate(record.helperOnlineTime)}</div>
            ) : (
              ''
            )}
          </>
        );
      },
    },
    {
      title: '在线用户',
      dataIndex: 'userCount',
      // align: 'center',
      //sorter: true,
      sorter: (a, b) => (a.userCount ?? 0) - (b.userCount ?? 0),
      width: 90,
      render: (_, record) => {
        return (
          <>
            {record.userCount}
            <a
              key="online_ips"
              onClick={(e) => {
                setFormReportIpVisible(true);
                setCurrentGroup(undefined);
                setCurrent(record);
              }}
            >
              &nbsp;
              <ProfileOutlined />
            </a>
          </>
        );
      },
    },
    {
      title: '下载',
      // align: 'center',
      dataIndex: 'download',
      sorter: (a, b) => (a.download ?? 0) - (b.download ?? 0),
      width: 100,
      render: (_, record) => {
        return (
          <Tag
            color={
              record.download
                ? record.download <= alertGreen
                  ? 'green'
                  : record.download <= alertOrange
                  ? 'orange'
                  : 'red'
                : ''
            }
          >
            <b>
              <ArrowDownOutlined /> {utils.formatRate(record.download, true)}
            </b>
          </Tag>
        );
      },
    },
    {
      title: '上传',
      // align: 'center',
      dataIndex: 'upload',
      sorter: (a, b) => (a.upload ?? 0) - (b.upload ?? 0),
      width: 120,
      render: (_, record) => {
        return (
          <span>
            <Tag
              color={
                record.upload
                  ? record.upload <= alertGreen
                    ? 'green'
                    : record.upload <= alertOrange
                    ? 'orange'
                    : 'red'
                  : ''
              }
            >
              <b>
                <ArrowUpOutlined /> {utils.formatRate(record.upload, true)}
              </b>
            </Tag>

            <a
              key="edit"
              onClick={(e) => {
                // setFormNodeVisible(true);
                // setCurrentNode(record);
                setFormGrafanaVisible(true);
                setCurrentNode(record);
                setCurrentNodeGroup(undefined);
                // setCurrentUrlGrafana(urlGrafanaNode);
                setCurrentUrlGrafana(globalGrafanaModel?.urlGrafanaNode);
                setLevelGroups(undefined);
              }}
            >
              <AreaChartOutlined />
            </a>
          </span>
        );
      },
    },
    {
      title: 'CPU',
      // align: 'center',
      dataIndex: 'cpuUsed',
      width: 100,
      sorter: (a, b) => (a.cpuUsed ?? 0) - (b.cpuUsed ?? 0),
      render: (_, record) => {
        return (
          <Tag
            color={
              record.cpuUsed
                ? record.cpuUsed < 0.5
                  ? 'green'
                  : record.cpuUsed < 0.9
                  ? 'orange'
                  : 'red'
                : ''
            }
          >
            <b>
              {record.cpuCore} / {utils.formatPercentage(record.cpuUsed, 1)}%
            </b>
          </Tag>
        );
      },
    },
    {
      title: '内存',
      dataIndex: 'memUsedPer',
      // align: 'center',
      width: 120,
      sorter: (a, b) => (a.memUsedPer ?? 0) - (b.memUsedPer ?? 0),
      render: (_, record) => {
        let usedPer = record.memUsedPer ?? 0;
        return (
          <Tag
            color={
              usedPer != 0
                ? usedPer < 0.5
                  ? 'green'
                  : usedPer < 0.9
                  ? 'orange'
                  : 'red'
                : ''
            }
          >
            <b>
              {utils.formatRate(record.memTotal, true)} /{' '}
              {utils.formatPercentage(usedPer, 1)}%
            </b>
          </Tag>
        );
      },
    },
    {
      title: '版本',
      dataIndex: 'version',
      // align: 'center',
      width: 60,
      sorter: (a, b) => (a.version ?? '').localeCompare(b.version ?? ''),
    },
    {
      title: '启动时间',
      // align: 'center',
      dataIndex: 'startTime',
      sorter: (a, b) =>
        utils
          .formatUtcToLocal(a.startTime)
          .localeCompare(utils.formatUtcToLocal(b.startTime)),
      width: 180,
      render: (_, record) => {
        return (
          <>
            {record.startTime ? (
              <div>启动: {utils.formatUtcToLocal(record.startTime)}</div>
            ) : (
              ''
            )}
            <div>
            <CheckLogTipTag 
              checkAuto={record.checkAuto} 
              checkPercent={record.checkPercent}
              checkTime={record.checkTime}
              checkInterval={monitorData.checkInterval} 
              displayPrefix={true}              
              checkFalse={undefined}
            />
            </div>
            <div>
            <DeployLogStatusTag log={record.serverInfo?.deployLog} />
            </div>
          </>
        );
      },
    },
    {
      title: '带宽限制',
      // align: 'center',
      dataIndex: 'maxBandwidth',
      width: 90,
      sorter: (a, b) => (a.maxBandwidth ?? 0) - (b.maxBandwidth ?? 0),
      render: (_, record) => {
        return (
          <>
            {(record.maxBandwidth as number) > 0
              ? `T:${record.maxBandwidth}`
              : ''}
            {(record.maxUserBandwidth as number) > 0
              ? ` U:${record.maxUserBandwidth}`
              : ''}
          </>
        );
      },
    },
    {
      title: '价格',
      // align: 'center',
      dataIndex: 'price',
      width: 60,
      // sorter: (a, b) => ((a.serverInfo?.price) ?? 0) - ((b.serverInfo?.price) ?? 0),
      render: (_, record) => {
        return record.serverInfo?.price;
      },
    },
    {
      title: '上架日期',
      // align: 'center',
      dataIndex: 'addedDate',
      width: 90,
      render: (_, record) => {
        return (
          <>
            <div>
              {record.addedDate
                ? dayjs(record.addedDate).format(dateFormat)
                : ''}
            </div>
            <div>{record.createUser}</div>
          </>
        );
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      sorter: (a, b) => (a.remark ?? '').localeCompare(b.remark ?? ''),
      ellipsis: true,
    },
  ];

  childrenColumns = childrenColumns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 160,
      render: (_, record) => {
        let cmps = [];

        if (hasRight('vpnserver_update')) {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要换IP吗?"
              onConfirm={async () => {
                await handleChangeIp(record.supplierId, record.instanceId);
              }}
            >
              <a>换IP</a>
            </Popconfirm>,

            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }
        
        if (hasRight('deploy_create')){
          cmps.push(
            <a
              onClick={async () => {
                setFormDeployVisible(true);
                setSelectServer([record]);
              }}
            >
              部署
            </a>
          );
        }

          cmps.push(
            <a
              key="check"
              onClick={(e) => {
                handleCheckServer(record);
              }}
            >
              X检测
            </a>,
            // <Popconfirm
            //   key="check"
            //   title="确定要检测该服务器吗?"
            //   onConfirm={async () => {
            //     await handleCheck("server", record.id);
            //   }}
            // >
            //   <a>检测</a>
            // </Popconfirm>,
          );

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable<API.VpnGroupMonitorModel>
        rowKey="id"
        actionRef={actionRef}
        formRef={formRef}
        options={{
          fullScreen: false,
          reload: false,
          // setting: false,
          density: false,
          // search:true,
          // setting: {
          //   listsHeight: 500,
          // },
        }}
        loading={dataLoading}
        search={false}
        pagination={false}
        columns={columns}
        columnsState={{
          value: columnsStateMap,
          onChange: setColumnsStateMap,
        }}
        expandable={{
          expandedRowRender: (record) => (
            <ProTable
              columns={childrenColumns}
              headerTitle={false}
              search={false}
              options={false}
              dataSource={record.data}
              tableStyle={{ marginLeft: 10 }}
              // pagination={false}
              pagination={{
                defaultPageSize: 50,
                pageSizeOptions: [
                  '50',
                  '100',
                  '200',
                  '300',
                  '500',
                  '1000',
                  '2000',
                  '5000',
                  '10000',
                ],
                hideOnSinglePage: false,
                // current: pageCurrent,
                // total: totalCount,
              }}
            />
            // <MyVirtualTable columns={childrenVirtualColumns} dataSource={record.data} scroll={{ y: 54 * record.data.length + 100, x: '100vw' }} />
          ),
          // defaultExpandedRowKeys: ['0'],
          // expandedRowKeys:groupExpandedRowKeys,
          // onExpandedRowsChange: (expandedKeys) => {
          //     // console.log(expandedKeys);
          //     setGroupExpandedRowKeys(expandedKeys);
          // },
        }}
        toolBarRender={() => [
          <span>
            <Button
              key="check_task"
              type="primary"
              onClick={() => {
                setFormCheckTaskVisible(true);
              }}
            >
              X检测
            </Button>
            &nbsp;
            <Button
              key="check_biubiu"
              onClick={() => {
                setFormCheckVisible(true);
              }}
            >
              Biu检测
            </Button>
            &nbsp;
            <Button
              key="check_biubiu_report"
              onClick={() => {
                setCurrentVer(undefined);
                setFormCheckReportVisible(true);
              }}
            >
              Biu检测结果
            </Button>
            &nbsp;
            <Popconfirm
              key="syncIps"
              title="确定要开始同步IP吗?"
              onConfirm={async () => {
                setFormSyncIpVisible(true);
              }}
            >
              <Button type="primary">同步IP</Button>
            </Popconfirm>
            &nbsp;
            <Button
              key="btn_export_ip"
              // type="primary"
              onClick={() => {
                setFormExportIpVisible(true);
              }}
            >
              导IP
            </Button>
            &nbsp;&nbsp;
            <Space>
              <Countdown
                title=""
                key="cdRefresh"
                value={countdownTicks}
                format="s"
                prefix=""
                suffix="秒"
                valueStyle={{
                  fontSize: 14,
                  color: 'gray',
                }}
                // style={{ visibility: countdownVisible }}
                onFinish={reload}
              />
            </Space>
            <span>
              <a
                onClick={() => {
                  setDataLoading(true);
                  reload();
                }}
              >
                <ReloadOutlined />
              </a>
            </span>
          </span>,
        ]}
        title={() => (
          <>
            {
              // (filterAreaPolicy && filterAreaPolicy != -1)
              //   || (filterMemberLevel.length > 1 || filterMemberLevel.length == 0 && filterMemberLevel[0] != -1)
              //   || (filterOnline && filterOnline != -1) || (filterStatus == false || filterStatus == true)
              //   || (filterTag.length > 1 || filterTag.length == 0 && filterTag[0] != '-1') ?
              monitorData?.hasFilter == true ? (
                <Row gutter={24} style={{ marginBottom: 10 }}>
                  <Col span={24}>
                    <Tag color="#3b5999">
                      <span style={{ fontSize: 13 }}>流量</span>
                    </Tag>
                    <a
                      onClick={(e) => {
                        setFormGrafanaVisible(true);
                        setCurrentNode(undefined);
                        setCurrentNodeGroup(undefined);
                        setCurrentUrlGrafana(
                          globalGrafanaModel?.urlGrafanaNodeAll,
                        );
                        setLevelGroups(undefined);
                      }}
                      style={{ color: 'green' }}
                    >
                      <AreaChartOutlined />总
                    </a>
                    &nbsp;
                    <Tag color="green">
                      <b>
                        <ArrowDownOutlined />
                        {utils.formatRate(
                          monitorData?.filterTotalDownload,
                          true,
                        )}
                        &nbsp;&nbsp;
                        <ArrowUpOutlined />
                        {utils.formatRate(monitorData?.filterTotalUpload, true)}
                      </b>
                    </Tag>
                    <a
                      onClick={(e) => {
                        let groups: API.VpnGroupMonitorModel[] = [];
                        monitorData?.data.forEach((item) => {
                          if (item.memberLevel != 0 && item.memberLevel != 1) {
                            groups.push(item);
                          }
                        });
                        setLevelGroups(groups);
                        setGrafanaTitle('VIP分组总流量');

                        setFormGrafanaVisible(true);
                        setCurrentNode(undefined);
                        setCurrentNodeGroup(undefined);
                        setCurrentUrlGrafana(
                          globalGrafanaModel?.urlGrafanaNodeGroup,
                        );
                      }}
                      style={{ color: 'green' }}
                    >
                      <AreaChartOutlined />
                      VIP
                    </a>
                    &nbsp;
                    <Tag color="green">
                      <b>
                        <ArrowDownOutlined />
                        {utils.formatRate(
                          monitorData?.filterTotalVipDownload,
                          true,
                        )}
                      </b>
                      &nbsp;&nbsp;
                      <b>
                        <ArrowUpOutlined />
                        {utils.formatRate(
                          monitorData?.filterTotalVipUpload,
                          true,
                        )}
                      </b>
                    </Tag>
                    <a
                      onClick={(e) => {
                        let groups: API.VpnGroupMonitorModel[] = [];
                        monitorData?.data.forEach((item) => {
                          if (item.memberLevel == 0 || item.memberLevel == 1) {
                            groups.push(item);
                          }
                        });
                        setLevelGroups(groups);
                        setGrafanaTitle('Free分组总流量');

                        setFormGrafanaVisible(true);
                        setCurrentNode(undefined);
                        setCurrentNodeGroup(undefined);
                        setCurrentUrlGrafana(
                          globalGrafanaModel?.urlGrafanaNodeGroup,
                        );
                      }}
                      style={{ color: 'green' }}
                    >
                      <AreaChartOutlined />
                      Free
                    </a>
                    &nbsp;
                    <Tag color="green">
                      <b>
                        <ArrowDownOutlined />
                        {utils.formatRate(
                          monitorData?.filterTotalFreeDownload,
                          true,
                        )}
                      </b>
                      &nbsp;&nbsp;
                      <b>
                        <ArrowUpOutlined />
                        {utils.formatRate(
                          monitorData?.filterTotalFreeUpload,
                          true,
                        )}
                      </b>
                    </Tag>
                    &nbsp;
                    <a
                      key="online_chart_total"
                      onClick={(e) => {
                        setFormOnlineVisible(true);
                        setCurrentGroup(undefined);
                        setCurrentOnlineCode('__total__');
                      }}
                      style={{ color: 'green' }}
                    >
                      <UserOutlined />
                    </a>
                    &nbsp;
                    <Tag color="green">
                      <b>
                        {utils.formatNumber(monitorData?.filterTotalUserCount)}{' '}
                        [
                        <a
                          key="online_chart_free"
                          onClick={(e) => {
                            setFormOnlineVisible(true);
                            setCurrentGroup(undefined);
                            setCurrentOnlineCode('__free__');
                          }}
                          // style={{ color: '#096DD9' }}
                          style={{ color: 'green' }}
                        >
                          &nbsp;
                          <AreaChartOutlined />
                        </a>
                        F:
                        {utils.formatNumber(
                          monitorData?.filterTotalFreeUserCount,
                        )}{' '}
                        /
                        <a
                          key="online_chart_vip"
                          onClick={(e) => {
                            setFormOnlineVisible(true);
                            setCurrentGroup(undefined);
                            setCurrentOnlineCode('__vip__');
                          }}
                          // style={{ color: '#096DD9' }}
                          style={{ color: 'green' }}
                        >
                          &nbsp;
                          <AreaChartOutlined />
                        </a>
                        V:
                        {utils.formatNumber(
                          monitorData?.filterTotalVipUserCount,
                        )}
                        ]
                      </b>
                    </Tag>
                    <Tag color="#3b5999">
                      <span style={{ fontSize: 13 }}>服务器</span>
                    </Tag>
                    <Tag color="green">
                      <b>
                        启用:{' '}
                        {utils.formatNumber(
                          monitorData?.filterTotalValidServerCount,
                        )}{' '}
                        / 禁用:{' '}
                        {utils.formatNumber(
                          (monitorData?.filterTotalServerCount ?? 0) -
                            (monitorData?.filterTotalValidServerCount ?? 0),
                        )}{' '}
                        / 总数:{' '}
                        {utils.formatNumber(
                          monitorData?.filterTotalServerCount,
                        )}
                      </b>
                    </Tag>
                    <Tag color="green">
                      <b>
                        离线:{' '}
                        {utils.formatNumber(
                          monitorData?.filterTotalOfflineCount,
                        )}{' '}
                        / 在线:{' '}
                        {utils.formatNumber(
                          monitorData?.filterTotalOnlineCount,
                        )}
                      </b>
                    </Tag>
                  </Col>
                </Row>
              ) : (
                ''
              )
            }

            <Row gutter={24} style={{ marginBottom: 10 }}>
              <Col span={24}>
                <Tag color="#3b5999">
                  <span style={{ fontSize: 13 }}>流量</span>
                </Tag>
                <a
                  onClick={(e) => {
                    setFormGrafanaVisible(true);
                    setCurrentNode(undefined);
                    setCurrentNodeGroup(undefined);
                    setCurrentUrlGrafana(globalGrafanaModel?.urlGrafanaNodeAll);
                    setLevelGroups(undefined);
                  }}
                >
                  <AreaChartOutlined />总
                </a>
                &nbsp;
                <Tag color="blue">
                  <b>
                    <ArrowDownOutlined />
                    {utils.formatRate(monitorData?.totalDownload, true)}
                    &nbsp;&nbsp;
                    <ArrowUpOutlined />
                    {utils.formatRate(monitorData?.totalUpload, true)}
                  </b>
                </Tag>
                <a
                  onClick={(e) => {
                    let groups: API.VpnGroupMonitorModel[] = [];
                    monitorData?.data.forEach((item) => {
                      if (item.memberLevel != 0 && item.memberLevel != 1) {
                        groups.push(item);
                      }
                    });
                    setLevelGroups(groups);
                    setGrafanaTitle('VIP分组总流量');

                    setFormGrafanaVisible(true);
                    setCurrentNode(undefined);
                    setCurrentNodeGroup(undefined);
                    setCurrentUrlGrafana(
                      globalGrafanaModel?.urlGrafanaNodeGroup,
                    );
                  }}
                >
                  <AreaChartOutlined />
                  VIP
                </a>
                &nbsp;
                <Tag color="blue">
                  <b>
                    <ArrowDownOutlined />
                    {utils.formatRate(monitorData?.totalVipDownload, true)}
                  </b>
                  &nbsp;&nbsp;
                  <b>
                    <ArrowUpOutlined />
                    {utils.formatRate(monitorData?.totalVipUpload, true)}
                  </b>
                </Tag>
                <a
                  onClick={(e) => {
                    let groups: API.VpnGroupMonitorModel[] = [];
                    monitorData?.data.forEach((item) => {
                      if (item.memberLevel == 0 || item.memberLevel == 1) {
                        groups.push(item);
                      }
                    });
                    setLevelGroups(groups);
                    setGrafanaTitle('Free分组总流量');

                    setFormGrafanaVisible(true);
                    setCurrentNode(undefined);
                    setCurrentNodeGroup(undefined);
                    setCurrentUrlGrafana(
                      globalGrafanaModel?.urlGrafanaNodeGroup,
                    );
                  }}
                >
                  <AreaChartOutlined />
                  Free
                </a>
                &nbsp;
                <Tag color="blue">
                  <b>
                    <ArrowDownOutlined />
                    {utils.formatRate(monitorData?.totalFreeDownload, true)}
                  </b>
                  &nbsp;&nbsp;
                  <b>
                    <ArrowUpOutlined />
                    {utils.formatRate(monitorData?.totalFreeUpload, true)}
                  </b>
                </Tag>
                &nbsp;
                <a
                  key="online_chart_total"
                  onClick={(e) => {
                    setFormOnlineVisible(true);
                    setCurrentGroup(undefined);
                    setCurrentOnlineCode('__total__');
                  }}
                >
                  <UserOutlined />
                </a>
                &nbsp;
                <Tag color="blue">
                  <b>
                    {utils.formatNumber(monitorData?.totalUserCount)} [
                    <a
                      key="online_chart_free"
                      onClick={(e) => {
                        setFormOnlineVisible(true);
                        setCurrentGroup(undefined);
                        setCurrentOnlineCode('__free__');
                      }}
                      style={{ color: '#096DD9' }}
                    >
                      &nbsp;
                      <AreaChartOutlined />
                    </a>
                    F:
                    {utils.formatNumber(monitorData?.totalFreeUserCount)} /
                    <a
                      key="online_chart_vip"
                      onClick={(e) => {
                        setFormOnlineVisible(true);
                        setCurrentGroup(undefined);
                        setCurrentOnlineCode('__vip__');
                      }}
                      style={{ color: '#096DD9' }}
                    >
                      &nbsp;
                      <AreaChartOutlined />
                    </a>
                    V:
                    {utils.formatNumber(monitorData?.totalVipUserCount)}]
                  </b>
                </Tag>
                <Tag color="#3b5999">
                  <span style={{ fontSize: 13 }}>服务器</span>
                </Tag>
                <Tag color="blue">
                  <b>
                    启用:{' '}
                    {utils.formatNumber(monitorData?.totalValidServerCount)} /{' '}
                    禁用:{' '}
                    {utils.formatNumber(
                      (monitorData?.totalServerCount ?? 0) -
                        (monitorData?.totalValidServerCount ?? 0),
                    )}{' '}
                    / 总数: {utils.formatNumber(monitorData?.totalServerCount)}
                  </b>
                </Tag>
                <Tag color="blue">
                  <b>
                    离线: {utils.formatNumber(monitorData?.totalOfflineCount)} /{' '}
                    在线: {utils.formatNumber(monitorData?.totalOnlineCount)}
                  </b>
                </Tag>
              </Col>
            </Row>

            <Row gutter={24} style={{ marginBottom: 10 }}>
              <Col span={24}>
                <Tag color="#3b5999">
                  <span style={{ fontSize: 13 }}>在线状态</span>
                </Tag>
                <Radio.Group
                  defaultValue={
                    filterOnline == 1 ? 'b' : filterOnline == 0 ? 'c' : 'a'
                  }
                  // buttonStyle="solid"
                >
                  <Radio
                    value="a"
                    onClick={() => {
                      setFilterOnline(undefined);
                    }}
                  >
                    全部
                  </Radio>
                  <Radio
                    value="b"
                    onClick={() => {
                      setFilterOnline(1);
                    }}
                  >
                    在线
                  </Radio>
                  <Radio
                    value="c"
                    onClick={() => {
                      setFilterOnline(0);
                    }}
                  >
                    离线
                  </Radio>
                </Radio.Group>
                <Tag color="#3b5999">
                  <span style={{ fontSize: 13 }}>状态</span>
                </Tag>
                <Radio.Group
                  defaultValue={
                    filterOnline == 1 ? 'b' : filterOnline == 0 ? 'c' : 'a'
                  }
                  // buttonStyle="solid"
                >
                  <Radio
                    value="a"
                    onClick={() => {
                      setFilterStatus(undefined);
                    }}
                  >
                    全部
                  </Radio>
                  <Radio
                    value="b"
                    onClick={() => {
                      setFilterStatus(true);
                    }}
                  >
                    启用
                  </Radio>
                  <Radio
                    value="c"
                    onClick={() => {
                      setFilterStatus(false);
                    }}
                  >
                    禁用
                  </Radio>
                </Radio.Group>
                <Tag color="#3b5999">
                  <span style={{ fontSize: 13 }}>地区策略</span>
                </Tag>
                <Radio.Group defaultValue="a">
                  <Radio
                    value="a"
                    onClick={() => {
                      setFilterAreaPolicy(undefined);
                    }}
                  >
                    全部
                  </Radio>
                  <Radio
                    value="b"
                    onClick={() => {
                      setFilterAreaPolicy(3);
                    }}
                  >
                    显示: 中国大陆
                  </Radio>
                  <Radio
                    value="c"
                    onClick={() => {
                      setFilterAreaPolicy(2);
                    }}
                  >
                    隐藏: 伊朗
                  </Radio>
                </Radio.Group>
                <Tag color="#3b5999">
                  <span style={{ fontSize: 13 }}>等级</span>
                </Tag>
                <Checkbox.Group
                  key="ckgMemberLevel"
                  onChange={(checkedValue) => {
                    // setFilterMemberLevel(checkedValue);
                    handleFilterMemberLevel(checkedValue);
                    // console.log(checkedValue);
                  }}
                  value={filterMemberLevel}
                  options={[{ label: '全部', value: -1, key: -1 }].concat(
                    c.MemberLevelOptions,
                  )}
                ></Checkbox.Group>
                <Tag color="#3b5999">
                  <span style={{ fontSize: 13 }}>类型</span>
                </Tag>
                <Checkbox.Group
                  key="ckgGroupType"
                  onChange={(checkedValue) => {
                    // setFilterGroupType(checkedValue);
                    handleFilterGroupType(checkedValue);
                    // console.log(checkedValue);
                  }}
                  value={filterGroupType}
                  options={[{ label: '全部', value: 'all' },{ label: '桥接', value: 'bridge' }]}
                ></Checkbox.Group>
                &nbsp;
                <Button
                  type="primary"
                  ghost
                  key="check_reset"
                  onClick={() => {
                    handleFilterReset();
                  }}
                >
                  恢复默认
                </Button>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col span={24}>
                {/* <a
                onClick={async () => {
                  setGroupExpandedRowKeys([]);
                }}
              >
                <Tag color='#3b5999'><span style={{fontSize:13}}><UpSquareOutlined />全部折叠</span></Tag>
              </a> */}

                <Tag color="#3b5999">
                  <span style={{ fontSize: 13 }}>标签</span>
                </Tag>
                <Checkbox.Group
                  key="ckgTag"
                  onChange={(checkedValue) => {
                    handleFilterTag(checkedValue);
                    // console.log(checkedValue);
                  }}
                  value={filterTag}
                  options={[{ label: '全部', value: '-1', key: '-1' }].concat(
                    getTagOptions(),
                  )}
                ></Checkbox.Group>
              </Col>
            </Row>
          </>
        )}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: productId,
            items: productMenuItems,
            onChange: (tabKey) => {
              setProductId(tabKey as string);
            },
          },
        }}
        dataSource={monitorData?.data}
      />

      <VpnServerForm
        visible={formVisible}
        defaultGroupIds={undefined}
        loadNodeId={current?.id}
        onSubmit={() => {
          setDeployConfigPublish(true);
          setCurrent(undefined);
          setFormVisible(false);
          reload();
        }}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
      <GrafanaForm
        visible={formGrafanaVisible}
        group={currentNodeGroup}
        server={currentNode}
        urlGrafana={currentUrlGrafana}
        groups={levelGroups}
        grafanaTitle={grafanaTitle}
        onCancel={() => {
          setFormGrafanaVisible(false);
          setCurrentNode(undefined);
          setCurrentNodeGroup(undefined);
          setCurrentUrlGrafana(undefined);
          setLevelGroups(undefined);
          setGrafanaTitle(undefined);
        }}
      />
      <CheckForm
        visible={formCheckVisible}
        groupIds={checkGroupIds}
        // groups={checkGroups}
        servers={checkServers}
        serverType={1}
        instIds={checkServerInstIds}
        onCancel={() => {
          setFormCheckVisible(false);
        }}
        onSubmit={checkFormSubmit}
      />
      <CheckReportForm
        visible={formCheckReportVisible}
        ver={currentVer}
        groupId={currentNodeGroup?.id}
        onCancel={() => {
          setFormCheckReportVisible(false);
          setCurrentNodeGroup(undefined);
          setCurrentVer(undefined);
        }}
        onCancelAndReload={() => {
          setFormCheckReportVisible(false);
          setCurrentNodeGroup(undefined);
          setCurrentVer(undefined);
        }}
      />
      <GroupForm
        visible={formGroupVisible}
        loadGroupId={undefined}
        current={currentGroup}
        parent={undefined}
        onSubmit={handleFormGroupSubmit}
        onCancel={() => {
          setCountdownTicks(Date.now() + 60 * 1000);
          setFormGroupVisible(false);
          setCurrentGroup(undefined);
        }}
      />
      <OnlineForm
        visible={formOnlineVisible}
        current={currentGroup}
        code={currentOnlineCode}
        productId={productId}
        onCancel={() => {
          setFormOnlineVisible(false);
          setCurrentGroup(undefined);
        }}
      />
      <VpnServerExportIpForm
        visible={formExportIpVisible}
        onCancel={() => {
          setFormExportIpVisible(false);
        }}
      />
      <ReportIpForm
        visible={formReportIpVisible}
        current={current}
        group={currentGroup}
        onCancel={() => {
          setFormReportIpVisible(false);
          setCurrentGroup(undefined);
          setCurrent(undefined);
        }}
      />

      <CheckTaskForm
        visible={formCheckTaskVisible}
        groupIds={checkGroupIds}
        servers={checkServers}
        instIds={checkServerInstIds}
        onCancel={() => {
          setFormCheckTaskVisible(false);
          setCheckGroupIds([]);
          setCheckServerInstIds([]);
          setCheckServers([]);
        }}
        onSubmit={() => {
          setFormCheckTaskVisible(false);
          setCheckGroupIds([]);
          setCheckServerInstIds([]);
          setCheckServers([]);

          reload();
        }}
      />

      <SyncIpForm
        visible={formSyncIpVisible}
        onCancel={() => {
          setDeployConfigPublish(true);
          setFormSyncIpVisible(false);
          actionRef.current?.reload();
        }}
      />

      <CheckTaskReportForm
        visible={formCheckTaskReportVisible}
        ver={currentVer}
        groupId={currentNodeGroup?.id}
        onCancel={() => {
          setFormCheckTaskReportVisible(false);
        }}
        onCancelAndReload={() => {
          setFormCheckTaskReportVisible(false);
          actionRef.current?.reload();
        }}
      />
      <DeployForm
        visible={formDeployVisible}
        servers={selectServer}
        onSubmit={() => {
          setFormDeployVisible(false);
          actionRef.current?.clearSelected?.();
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setFormDeployVisible(false);
        }}
      />

    </PageContainer>
  );
};

export default VpnGroupTreeList;
